//
//  DXCompseController.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/13.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit
import SVProgressHUD
class DXCompseController:
    UIViewController,UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate,DXPictureHolderViewDelegate{
    
    var iskeyBoardAnmationing:Bool = true
    override func viewDidLoad() {
        super.viewDidLoad()
  
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardFramewillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emotionButtonSelected:", name: emotionButtonDidSelectedNotifity, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emotionButtonDeteleted", name: KEmotionButtonDetele, object: nil)
        setUpUI()
       
    }
    
    // MARK: - 通知的监听方法
    
    @objc private func emotionButtonDeteleted(){
//    删除文本内容 
    textView.deleteBackward()
    
    }
    @objc private func emotionButtonSelected(notifity:NSNotification){
        let emotion = notifity.userInfo!["obj"] as! DXEmotonModel
//        根据emotion的中类型判断是否emoji表情
        if emotion.isEmoji {
            
        let emojiString = (emotion.code! as NSString).emoji()
        textView.insertText(emojiString)
            
        }else {
//            生成图片附件
            let imgAttribute = DXEmotionAttachment(emotion: emotion)
            
           let imgAttibutM = imgAttribute.getAttributString(textView.font!)
//            将生成的富文本插入到textview
            textView.insertAttributeString(imgAttibutM)
            
        }
    }
    @objc private func keyBoardFramewillChange(notifity:NSNotification){

   let rect = notifity.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
    let keyEndFrame = rect.CGRectValue()

        
        let ty = view.height - keyEndFrame.origin.y
        toolBarView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(-ty)
        }
        
        if iskeyBoardAnmationing {
        
        UIView.animateWithDuration(0.25) { () -> Void in
            self.toolBarView.layoutIfNeeded()
        }
    }
}
    
    
    deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }

//    MARK:初始化UI
 private func setUpUI(){
//    设置背景色
    self.view.backgroundColor = UIColor.whiteColor()
 
//    设置NavigationItems
     setupNavigationItems()
     navigationItem.rightBarButtonItem?.enabled = false
    
//    添加textView
     view.addSubview(textView)
     textView.addSubview(pictureHolderView)
    pictureHolderView.hidden = true
    
//    添加toolBar
    view.addSubview(toolBarView)
    
    
//    设置代理
    textView.delegate = self
    pictureHolderView.holderViewDelegate = self
    
//    pictureHolderView添加Item点击事件的回调
    pictureHolderView.pictureHolderViewAddItemClickClosure = { [weak self] in
        
//        弹出pickViewController选择照片
        self?.getImagePickViewController()

    }
    
//    toolBarView点击事件的回调
    toolBarView.toolBarButtonClickClosure = {[weak self] (type)->() in
        switch type {
        
        case .TextViewToolBarTypePicture :
           logPrint("图片")
           
        self!.getImagePickViewController()
            
        case .TextViewToolBarTypeMention :
          logPrint("@")
        case .TextViewToolBarTypeTrend :
            logPrint("#")
        case .TextViewToolBarTypeEmoticon :
            logPrint("表情")
//            弹出键盘
            self!.switchKeyBoard()
            
        case .TextViewToolBarTypeAdd :
            logPrint("添加")
            
//        default : break
        
        }
    }
    
    
//    添加约束
    textView.snp_makeConstraints { (make) -> Void in
        make.edges.equalTo(view).offset(UIEdgeInsetsZero)
    }
    
    let pictureHolderW = view.width - 10
    pictureHolderView.snp_makeConstraints { (make) -> Void in
        make.centerX.equalTo(textView)
        make.top.equalTo(textView).offset(100)
        make.size.equalTo(CGSizeMake(pictureHolderW, pictureHolderW))
    }
    toolBarView.snp_makeConstraints { (make) -> Void in
        make.bottom.equalTo(view)
        make.leading.equalTo(view)
        make.size.equalTo(CGSizeMake(view.width, 35))
    }
    
 }
   // MARK: - 转换键盘
    private func switchKeyBoard (){
//        当textview的键盘是系统键盘时,成为表情键盘
        if textView.inputView == nil{
            
          self.toolBarView.isClickEmotonKeyBoard = true
            
            callEmotionKeyBoard(true)
            
        }else{
            callEmotionKeyBoard(false)
             self.toolBarView.isClickEmotonKeyBoard = false
        }
    }
    
    // MARK: - 是否弹出表情键盘
    private func callEmotionKeyBoard(isemotion:Bool){
        
        //        取消第一响应者
        iskeyBoardAnmationing = false
        textView.resignFirstResponder()
        //        设置表情键盘
        textView.inputView = isemotion ? emontionKeyBoard : nil
        //        成为第一响应者
        iskeyBoardAnmationing = true
        textView.becomeFirstResponder()
        
    }
    
//    MARK: - 设置NavigationItems按钮
  private func setupNavigationItems(){
//    设置左边Baritem
    navigationItem.leftBarButtonItem = UIBarButtonItem.customItem(title: "返回", imgName: nil, target: self, action: "backVc")
//    设置中间的item
    navigationItem.titleView  = navigationTitleLabel
//    设置rightitem
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: navigationRightButton)
    
 }
//   MARK: - 点击发送微博
 @objc  private func sendWeiBo(){

//    判断是否发布文字或者是上传图片
    pictureHolderView.pictures.count == 0 ? statuesUpdata() : statuesUpload()
    
    }

    // MARK: - 点击返回按钮
    @objc private func backVc(){
        
//        退出控制器前退出键盘
        view.endEditing(true)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.25 * Double( NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
           
            self.dismissViewControllerAnimated(true, completion: nil)
        }

        
    
    }
//     MARK: - 发送微博文字方法
    private func statuesUpdata(){
    
        DXNetWorkClient.statuesUpdata(textView.statuesText, sucessClosure: { (responser) -> () in
            self.textView.attributedText =  NSAttributedString()
            SVProgressHUD.showSuccessWithStatus("成功")
            }) { (error) -> () in
                logPrint(error)
                SVProgressHUD.showSuccessWithStatus("失败")

        }
    }
//     MARK: - 发送图片微博的方法
    private func statuesUpload(){
        DXNetWorkClient.statuesUpload(textView.text, imge:pictureHolderView.pictures.first!, sucessClosure: { (responser) -> () in
            
            
           self.pictureHolderView.pictures.removeAll()
            
            SVProgressHUD.showSuccessWithStatus("成功")
            
            }) { (error) -> () in
                SVProgressHUD.showSuccessWithStatus("失败")
        }
    }


    
//    MARK:获取相册照片
    private func getImagePickViewController(){
    
        let pickVc = UIImagePickerController()
        pickVc.delegate = self
        
        presentViewController(pickVc, animated: true) { () -> Void in
        }
    }
    
//    MARK: - 懒加载
    
    lazy var navigationTitleLabel:UILabel = {
     let navigationTitleLabel = UILabel()
//        设置属性
        navigationTitleLabel.textAlignment = .Center
        navigationTitleLabel.numberOfLines = 0
     
        let userName = DXUserAccountViewModel.shareUserAccount.userAccount?.screen_name
        let string = "发微博\n\(userName!)"
        let attriString = NSMutableAttributedString(string:string)
        
        let userNameAttri = [
            NSFontAttributeName:UIFont.systemFontOfSize(12),
            NSForegroundColorAttributeName:UIColor.orangeColor()
        ]
     let userNamerange = subStringRangeOfStr(str: string, subString: userName!)
//        设置富文本的属性
        attriString.addAttributes(userNameAttri, range: userNamerange)
        
        let preAttrs = [
            NSFontAttributeName:UIFont.systemFontOfSize(15),
            NSForegroundColorAttributeName:UIColor.lightGrayColor()
        ]
        let preRange = subStringRangeOfStr(str: string, subString:"发微博")
        //        设置富文本的属性
        attriString.addAttributes(preAttrs, range: preRange)
        
        navigationTitleLabel.attributedText = attriString
        navigationTitleLabel.sizeToFit()
        return navigationTitleLabel
    }()

//   navigationRightButton
    lazy var navigationRightButton:UIButton = {
    let navigationRightButton = UIButton()
        navigationRightButton.width = 50
        navigationRightButton.height = 30
        navigationRightButton.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
         navigationRightButton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
         navigationRightButton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        navigationRightButton.setTitle("发送", forState: .Normal)
        navigationRightButton.titleLabel?.font = UIFont.systemFontOfSize(13)
        navigationRightButton.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
        navigationRightButton.addTarget(self, action: "sendWeiBo", forControlEvents: .TouchUpInside)
    return navigationRightButton
    }()
//    textView
    lazy var textView:DXTextView = {
    let textView = DXTextView()
        textView.font = UIFont.systemFontOfSize(14)
    textView.placeHoldText = "分享新鲜事..."
        return textView
    }()
    
//    pictureHolderView
    lazy var pictureHolderView:DXPictureHolderView = DXPictureHolderView()
    
    lazy var toolBarView:DXTextViewToolBar = {
    
    let toolBar = DXTextViewToolBar(frame: CGRectMake(0, 0,self.textView.width, 35))
   
        return toolBar
    }()
//    emontionKeyBoard
    lazy var emontionKeyBoard:DXEmontionKeyBoard = {
     
        let emontionKeyBoard = DXEmontionKeyBoard(frame: CGRectMake(0, 0, KScreenW, 200))
        
        return emontionKeyBoard
    }()

}

// MARK:UITextViewDelegate,UIImagePickerControllerDelegate,UIScrollView代理方法
extension DXCompseController{

    func pictureHolderViewPicturesChanged() {
    self.navigationItem.rightBarButtonItem?.enabled = self.pictureHolderView.hasPicture
    }
    
    func textViewDidChange(textView: UITextView) {
         navigationItem.rightBarButtonItem?.enabled = (textView as! DXTextView).hasContentText
    }
    
//    选择图片后的代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//    MARK:  向pictureHolderView中添加照片
        pictureHolderView.addImage(image.scaleImage(300))
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        view.endEditing(true)
    }
}
